'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 审核功能--拒绝玩家加入公会
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../../consts/code');
var unionGroupConf = require('../../../../config/unionGroupConf');
var unionGroupModel = require('../../../../models/unionGroupModel');
var unionPositionType = require('../../../../consts/unionPositionType');
var PlayerManager = require('../../../../libs/playerManager');

/**
 * 拒绝玩家加入公会
 */

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var union_user_id = msg.union_user_id;

    if (!union_user_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var union_user_manager = new PlayerManager(union_user_id);
    var union_group_model;
    var union_id;
    var union_member_num;

    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                ['role', 'accrued'],
                    cb
                );
            },
            function (cb) {
                if (!!union_id) {
                    unionGroupModel.getById(union_id, function (err, model) {
                        union_group_model = model;
                        cb();
                    });
                } else {
                    return next(null, {
                        code: Code.UNION_IS_NOT_JOIN
                    });
                }
            },
            function (cb) {

                // 权限是否达到
                if (!union_group_model.isBoss(role_id)) {
                    return next(null, {
                        code: Code.UNION_USER_NOT_BOOS
                    });
                }

                // 是否在公会申请列表中
                if (_.indexOf(union_group_model.apply_list, union_user_id) == -1) {
                    return next(null, {
                        code: Code.UNION_NOT_APPLY
                    });
                }

                // 移除审核列表信息
                union_group_model.removeApplyId(union_user_id);
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            union_group_model.save();
            return next(null, {
                code: Code.OK
            });
        }
    );
};
